package com.itao.springboot.service;

import lombok.AllArgsConstructor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

/**
 * @author sjt
 * @Date 2024/10/30 11:54
 */
@Service
@AllArgsConstructor
public class TaskService {
    private final Map<Long, ScheduledFuture<?>> map = new ConcurrentHashMap<>();

    private ThreadPoolTaskScheduler dynamicTaskScheduler;


    public void addTask(Runnable runnable, Long id) {

        ScheduledFuture<?> future = dynamicTaskScheduler.schedule(runnable, triggerContext -> {
            CronTrigger cronTrigger = new CronTrigger("*/10 * * * * ?");
            return cronTrigger.nextExecution(triggerContext);
        });
        map.put(id, future);
    }

    public void removeTask(Long id) {
        ScheduledFuture<?> future = map.remove(id);
        future.cancel(false);
    }
}
